package com.markix.configuration;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author markix
 * @date 2022/8/27 21:55
 */
public class ClientJwtTest {

    public static void main(String[] args) throws JOSEException {
        String clientId = "client3";
        String clientSecret = "01234567890123456789012345678912";

        // 至少以下四项信息
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                // 主体：固定clientId
                .subject(clientId)
                // 发行者：固定clientId
                .issuer(clientId)
                // 授权中心的地址
                .audience("http://localhost:9000")
                // 过期时间 24h
                .expirationTime(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                .build();

        String jwt = hmacSign(claimsSet, clientSecret);
        System.out.println(jwt);
        // eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbGllbnQxIiwic3ViIjoiY2xpZW50MSIsImF1ZCI6Imh0dHA6XC9cL2xvY2FsaG9zdDo5MDAwIiwiZXhwIjoxNjYxNjk5ODAzfQ.xpv_8w_R8LTZFID3uoQPn3CyQK_Bli3G-WTmrSrwayE
    }

    /**
     * 使用 HMAC 算法加签生成jwt
     */
    private static String hmacSign(JWTClaimsSet claimsSet, String secret) throws JOSEException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        JWSSigner signer = new MACSigner(secretKeySpec);

        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
        signedJWT.sign(signer);
        String token = signedJWT.serialize();
        return token;
    }

}
